package com.shujia.zookeeper;

import org.apache.hadoop.fs.Path;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class Code04GetChildrenNode {
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        int sessionTimeout = 5 * 1000;
        ZooKeeper zkCli = new ZooKeeper("master:2181,node1:2181,node2:2181", sessionTimeout, new Watcher() {
            // 处理监视结果
            @Override
            public void process(WatchedEvent event) {
                System.out.println("监视器被打开... 正在连接...");
            }
        });
        // public List<String> getChildren(final String path, Watcher watcher)
        String path = "/api";
        List<String> children = zkCli.getChildren(path, false);
        for (String child : children) {
            System.out.println("child:" + child);
            // 获取子节点中所有节点并且获取其数据
            String childPath = path + "/" + child;
            Stat exists = zkCli.exists(childPath, false);
            byte[] data = zkCli.getData(childPath, false, exists);
            // 如果获取到的节点为null直接跳过..
            if (data != null){
                String childData = new String(data);
                System.out.println("childPath: " + childData);
            }

        }
        zkCli.close();
    }
}
